/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package project2;
import project1.CandidateSolution;


/**
 *
 * @author rr
 */
public class TraverseSolver {
    private CandidateSolution solution = null;
    int n = SetUp.getInstance().getLengthOfSchedule() * SetUp.getInstance().getNumberOfEmployees();
    
    public void traverse(CandidateSolution thisSolution) {
        int n = SetUp.getInstance().getLengthOfSchedule() * SetUp.getInstance().getNumberOfEmployees();

        CandidateSolution[] solutions = new CandidateSolution[SetUp.getInstance().getNames().length];
        
        for(int i = 0; i<SetUp.getInstance().getNames().length; ++i){
            
            if(this.solution != null){
                return;
            }
            
            if(thisSolution.getPossibleAssignments()[i][thisSolution.getNextVariableIndex()] == true){
                solutions[i] = thisSolution.assignNext(i);

                //Run.printWorkSchedule(newSolution.getTempAssignments());
                
                if (solutions[i].getNumberOfAssignedValues() == n) {
                    this.solution = solutions[i];
                    return;
                }                  
                
            }
        }
        
        sort(solutions);
        
        for(int i = 0; i<SetUp.getInstance().getNames().length; ++i){
            if(this.solution != null){
                return;
            }
            
            if(solutions[i]!=null){
                if (solutions[i].getNumberOfAssignedValues() == n) {
                    this.solution = solutions[i];
                    return;
                } 
                if (solutions[i].getNextVariableIndex() != -1) {
                    //Run.printWorkSchedule(solutions[i].getTempAssignments());
                    this.traverse(solutions[i]);
                }
            }
        }
            
        
    }
    
    
    

    private void sort(CandidateSolution[] solutions) {
        for (int i = 0; i < solutions.length; i++) {
            for (int j = i + 1; j < solutions.length; j++) {
                if (solutions[i] != null && solutions[j] != null && solutions[i].getMinimumDomainSize() < solutions[j].getMinimumDomainSize()) {
                    CandidateSolution h = solutions[i];
                    solutions[i] = solutions[j];
                    solutions[j] = h;
                }
            }
        }
    }

    public CandidateSolution getSolution() {
        return solution;
    }

    public void setSolution(CandidateSolution solution) {
        this.solution = solution;
    }
    
    
}
